package com.wlanauth.web.action;

import java.util.List;

import org.hibernate.criterion.Restrictions;

import com.wlanauth.core.criteria.GeneralCriteria;
import com.wlanauth.core.criteria.GeneralCriteriaResult;
import com.wlanauth.domain.manage.SystemResource;
import com.wlanauth.web.core.BaseActionSupport;
import com.wlanauth.web.core.JsonResult;
import com.wlanauth.web.core.JsonResultConfig;
import com.wlanauth.web.core.SystemConstants;
import com.wlanauth.web.core.tree.INode;
import com.wlanauth.web.core.tree.TreeNode;
import com.wlanauth.web.core.tree.TreeUtil;
/**
 * 系统资源(用于简单权限管理)
 * @author zz
 * @date 2012-7-9
 * @email charles.zz.life@gmail.com
 */
public class SystemResourceAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;
	
	private SystemResource entity;
	
	public String list(){
		//通用查询
		GeneralCriteria criteria = this.buildWebQueryCriteria(SystemResource.class);
		
		if(entity!=null){
			if(entity.getCode()!=null){
				criteria.add(Restrictions.eq("code", entity.getCode()));
			}
			if(entity.getType()!=null){
				criteria.add(Restrictions.eq("type", entity.getType()));
			}
			
		}
		
		GeneralCriteriaResult<SystemResource> result = criteria.executeQuery();
		JsonResultConfig cfg = new JsonResultConfig();
		cfg.setExcludeProperties(new String[]{
				".*.roles"
		});
		this.jsonResult = new JsonResult(this,result.getData(),result.getTotal());
		return this.actionJsonResult(cfg);
	}
	
	public String getSystemResourceTree(){
		GeneralCriteria criteria = new GeneralCriteria(SystemResource.class);
		criteria.setDataOnly(false);
		criteria.add(Restrictions.eq("type",SystemResource.TYPE_MENU));
		
		GeneralCriteriaResult<SystemResource> result = criteria.executeQuery();
		TreeNode root = toTreeRootNode(result.getData());
		this.jsonResult = new JsonResult(this,root.getChildren(),true);
		return this.actionJsonResult();
	}
	
	private static TreeNode toTreeRootNode(List<SystemResource> list){
		
		SystemResource mRoot = new SystemResource();
		mRoot.setId(SystemConstants.ROLE_ROOT);
		mRoot.setName("根");
		mRoot.setParentId("");
		TreeNode root = TreeUtil.simpleToTree(mRoot,list,new INode(){
			public TreeNode entityToNode(Object obj){
				SystemResource m = (SystemResource)obj;
				TreeNode node = new TreeNode();
				node.setId(""+m.getId());
				node.setText(m.getName());
				node.setParentId(m.getParentId());
				node.setResourceCode(m.getCode());
				return node;
			}
		});
		return root;
	}
	public void setEntity(SystemResource entity) {
		this.entity = entity;
	}
	
}
